<!--
  * 调拨单表单
  *
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <!---------- 基本信息 begin ----------->
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="经销商" name="dealer_id" required>
              <Select name="Dealer" v-model:value="form.dealer_id" placeholder="经销商" @change="getWarehouseList"></Select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="调拨类型" name="transfer_type">
              <EnumSelect enum-name="TRANSFER_TYPE_ENUM" v-model:value="form.transfer_type" placeholder="请选择调拨类型" @change="transferChange" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="调拨方式" name="transfer_mode">
              <a-select v-model:value="form.transfer_mode" placeholder="请选择调拨方式">
                <a-select-option :value="1">司机配送</a-select-option>
                <a-select-option :value="2">货主自提</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="form.transfer_type">
            <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="调出仓库" name="start_warehouse_id" class="smart-query-form-item">
                <a-select v-model:value="form.start_warehouse_id" placeholder="请选择调出仓库">
                  <a-select-option v-for="item in startWarehouseList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="调入仓库" name="end_warehouse_id" class="smart-query-form-item">
                <a-select v-model:value="form.end_warehouse_id" placeholder="请选择调入仓库">
                  <a-select-option v-for="item in endWarehouseList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="备注">
              <a-input v-model:value="form.remark" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <!---------- 基本信息 end ----------->
      <!---------- 商品信息 begin ----------->
      <a-card title="商品信息" class="smart-margin-bottom10">
        <a-table size="small" :dataSource="form.detail" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false">
          <template #bodyCell="{ text, record, column, index }">
            <template v-if="column.dataIndex === 'index'">
              <div class="form-table-index">
                <span>{{ index + 1 }}</span>
                <div class="form-table-index-btn-wrap">
                  <div class="form-table-index-btn">
                    <div class="form-table-index-btn-item" @click="addFormDetail(index)">+</div>
                    <div class="form-table-index-btn-item" @click="delFormDetail(index)">-</div>
                  </div>
                </div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'goods_name'">
              <a-form-item class="form-table-item" required :name="['detail', index, 'goods_name']" :rules="[{ required: true, message: '请添加商品' }]">
                <a-input :value="text" readonly placeholder="请输入商品名称" size="small">
                  <template #suffix>
                    <a-button @click="showGoodsSelectModal(index)" type="link">多选</a-button>
                  </template>
                </a-input>
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'img'">
              <a-image :width="text ? 30 : 50" :src="record.goods_name ? text || failImg : ''" />
            </template>
            <template v-if="column.dataIndex === 'default_unit_type'">
              <a-radio-group v-model:value="record.default_unit_type" @change="onChangeUnit(index)" option-type="button" :options="_.map(record.spec, filterUnit)" />
            </template>
            <template v-if="column.dataIndex === 'transfer_num'">
              <a-form-item class="form-table-item">
                <a-input-number v-model:value="record.transfer_num" :min="1" @blur="validateQuantity(record)" />
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'sale_price'">
              {{ Number(text ?? 0).toFixed(2) }}
            </template>
            <template v-if="column.dataIndex === 'total'">
              {{ _.multiply(record?.transfer_num ?? 0, record?.sale_price ?? 0).toFixed(2) }}
            </template>
            <template v-if="column.dataIndex === 'remark'">
              <a-form-item class="form-table-item">
                <a-input v-model:value="record.remark" />
              </a-form-item>
            </template>
          </template>
        </a-table>
      </a-card>
      <!---------- 商品信息 end ----------->
    </a-form>
    <GoodsSelectModal ref="goodsSelectModalRef" :is_sold="1" checkStock @confirm="onSelectGoods" />
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { message } from 'ant-design-vue'
import Select from '@/components/business/select/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { searchApi } from '@/api/search/search-api'
import _ from 'lodash'
import { errorSentry } from '@/lib/error-sentry'
import GoodsSelectModal from '@/components/business/goods-select-modal/index.vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { transferOrderApi } from '@/api/business/storage/transfer-api'
import { APPLY_USER_ENUM } from '@/constants/business/storage/inwarehouse/transfer-const'
import failImg from '@/assets/images/notice/failImg.png'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reloadList'])

// 组件ref
const formRef = ref()
const formDefault = {
  // 经销商ID
  dealer_id: undefined,
  // 调拨类型
  transfer_type: undefined,
  // 调出仓库
  start_warehouse_id: null,
  // 调入仓库
  end_warehouse_id: null,
  // 调拨方式
  transfer_mode: null,
  // 备注
  remark: '',
  // 申请人类型
  apply_user_type: APPLY_USER_ENUM['COMPANY'].value,
  // 商品数据
  detail: [{}]
}
const form = ref<any>({ ..._.cloneDeep(formDefault) })
const rules = {
  transfer_type: [{ required: true, message: '请选择调拨类型' }],
  start_warehouse_id: [{ required: true, message: '请选择调出仓库' }],
  end_warehouse_id: [{ required: true, message: '请选择调入仓库' }],
  transfer_mode: [{ required: true, message: '请选择调拨方式' }]
}
// 商品数量验证
const validateQuantity = (record) => {
  // 检查是否为正整数
  if (!Number.isInteger(record.transfer_num) || record.transfer_num <= 0) {
    message.error('请输入正整数')
    record.transfer_num = 1 // 重置为默认值
  }
}
// ---------------------------- 展示抽屉 ----------------------------
const visible = ref(false)
function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (!_.isEmpty(rowData) && rowData?.id) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    form.value.detail = rowData.detail.map((item) => {
      return {
        ...item.goods,
        goods_id: item.goods_id,
        goods_spec_id: item.goods_spec_id,
        id: item.id,
        transfer_num: getSpecQuantity(item.transfer_num, item.spec),
        barcode: item.spec.barcode,
        sale_price: item.spec.sale_price,
        unit: item.spec.unit_name,
        spec_name: item.spec.spec_name,
        spec_stock: item.goods.sales_stock,
        spec_id: item.spec.id,
        conversion_rate: item.spec.conversion_rate,
        remark: item.remark
      }
    })
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  visible.value = false
}

async function onSubmit() {
  // 去除空行
  const validItems = unref(form).detail.filter((item) => !_.isEmpty(item) && item.transfer_num !== 0)
  if (validItems.length === 0) {
    message.error('请选择商品')
    return
  }
  form.value.detail = validItems
  await nextTick()

  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      const keys = ['transfer_num', 'goods_id', 'goods_spec_id', 'remark']
      const specData = _(form.value.detail)
        .cloneDeep()
        .map((item) => _.pick(item, keys))
      const data = {
        ...form.value,
        detail: JSON.stringify(specData)
      }
      try {
        if (form.value.id) {
          await transferOrderApi.update(data)
        } else {
          await transferOrderApi.create(data)
        }
        message.success('操作成功')
        onClose()
        emit('reloadList')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 商品选择弹窗
const goodsSelectModalRef = ref()
const modalIndex = ref(0)
// 记录点击多选按钮的表格行索引，插入数据时使用
function showGoodsSelectModal(index: number) {
  if (!form.value.start_warehouse_id) {
    message.error('请选择调出仓库')
    return
  }
  if (form.value.transfer_type === 1 && !form.value.dealer_id) {
    message.error('请选择经销商')
    return
  }
  modalIndex.value = index
  goodsSelectModalRef.value.showModal({ warehouse_id: form.value.start_warehouse_id, dealer_id: form.value.dealer_id })
}
// 商品选择回调
function onSelectGoods(goodsList) {
  // 处理商品数据
  function handleGoodsData(rowData) {
    const keys = ['goods_name', 'img', 'no', 'spec']
    const specData = _.find(rowData.spec, (item) => item.unit_type === rowData.default_unit_type)
    return {
      ..._.pick(rowData, keys),
      spec_stock: specData.availableQuantities,
      barcode: specData.barcode,
      unit: specData.unit_name,
      spec_name: specData.spec_name,
      spec_sale_price: specData.sale_price,
      goods_id: specData.goods_id,
      goods_spec_id: specData.id,
      transfer_num: 1,
      sale_price: Number(specData.sale_price),
      conversion_rate: specData.conversion_rate,
      remark: ''
    }
  }
  // 如果当前索引值有数据则覆盖
  const rows = _.map(goodsList, handleGoodsData)
  if (form.value.detail[modalIndex.value]) {
    form.value.detail.splice(modalIndex.value, 1, ...rows)
  } else {
    // 否则插入数据
    if (modalIndex.value === 0) {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value, 0, ...rows)
    } else {
      // 从modalIndex插入数据
      form.value.detail.splice(modalIndex.value + 1, 0, ...rows)
    }
  }
  // 自动追加一个空行
  if (!_.isEmpty(_.last(form.value.detail))) form.value.detail.push({})
}

// ----------------------------------  商品信息  ----------------------------------
// 表头配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: 160
  },
  {
    title: '图片',
    dataIndex: 'img'
  },
  {
    title: '规格条码',
    dataIndex: 'barcode'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  // {
  //   title: '库存',
  //   dataIndex: 'spec_stock'
  // },
  {
    title: '数量',
    dataIndex: 'transfer_num'
  },
  {
    title: '单价',
    dataIndex: 'sale_price'
  },
  {
    title: '小计',
    dataIndex: 'total'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  }
]
// 商品单位改变时需要同步修改行数据中的库存等
function onChangeUnit(index: number) {
  // 处理商品数据
  function handleGoodsData(rowData) {
    const specData = _.find(rowData.spec, (item) => item.unit_type === rowData.unit)
    return {
      ...rowData,
      spec_stock: specData.stock,
      spec_name: specData.name,
      spec_sale_price: specData.sale_price,
      goods_id: specData.dealer_goods_id,
      goods_spec_id: specData.id
    }
  }
  form.value.detail[index] = handleGoodsData(form.value.detail[index])
}
// 增加空行
function addFormDetail(index: number) {
  form.value.detail.splice(index + 1, 0, {})
}
// 删除行
function delFormDetail(index: number) {
  if (form.value.detail.length === 1) return
  form.value.detail.splice(index, 1)
}

// 过滤规格
function filterUnit(specData) {
  return {
    label: specData.spec_name,
    value: specData.unit_type
  }
}
// 调入库存隐藏
const inHide = ref(true)
// ---------------------------- 调拨类型选择 ----------------------------
const transferChange = (val) => {
  if (val == 3) {
    inHide.value = false
  } else {
    inHide.value = true
  }
  form.value.start_warehouse_id = null
  form.value.end_warehouse_id = null
}
// ---------------------------- 下拉框 ----------------------------
// 查询所有仓库数据
const warehouseList = ref<{ id: number; name: string; warehouse_type: 1 | 2 }[]>([])
async function getWarehouseList() {
  const params = {
    fields: 'id,name,warehouse_type'
  }
  const res = await searchApi.warehouseList(params)
  warehouseList.value = res.data
}

// 调出仓库数据
const startWarehouseList = computed(() => {
  const warehouse_type = [2, 4].includes(form.value.transfer_type) ? 2 : 1
  return warehouseList.value.filter((item) => item.warehouse_type === warehouse_type)
})

// 调入仓库数据
const endWarehouseList = computed(() => {
  const warehouse_type = [2, 4].includes(form.value.transfer_type) ? 1 : 2
  return warehouseList.value.filter((item) => item.warehouse_type === warehouse_type)
})

// 表单标题
const formTitle = computed(() => (form.id ? '编辑' : '新建'))
</script>
<style scoped lang="less">
.form-table-item {
  margin-bottom: 0;
  max-width: 200px;
}
.form-table-index {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  .form-table-index-btn-wrap {
    display: none;
  }
  .form-table-index-btn {
    display: flex;
  }
  .form-table-index-btn-item {
    width: 50%;
    height: 100%;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .form-table-index-btn-item:hover {
    background: #f87171ff;
    color: white;
  }
}
.form-table-index:hover span {
  display: none;
}
.form-table-index:hover .form-table-index-btn-wrap {
  display: block;
}
</style>
